﻿using ExcelAutomator.Configuration;
using ExcelAutomator.Validation;
using Microsoft.Office.Interop.Excel;

namespace ExcelAutomator.Executors.Range
{
	[Executor(ExecutorName, ExecutorType, ExecutorAction)]
	internal class RangeClearExecutor : Executor<RangeConfiguration>
	{
		public const string ExecutorName = "Range Clear Executor";
		public const string ExecutorType = "range";
		public const string ExecutorAction = "clear";

		public override ExecutionResult OnExecute(ExecutionContext context)
		{
			Worksheet worksheet;
			if(context.TargetWorkbook.TryGetWorksheet(Configuration.TargetAddress, out worksheet))
			{
				var targetRng = worksheet.get_Range(Configuration.TargetAddress, System.Type.Missing);
				targetRng.Clear();

				return ExecutionResult.CreateSuccess(string.Format("Clear Range '{0}'", Configuration.TargetAddress), context);
			}
			
			return ExecutionResult.CreateFailure(
				string.Format("Worksheet '{0}' does not exists", Configuration.TargetAddress.ExtractWorksheetNameFromAddress()), context);
		}

		public override void OnConfigure(string xmlConfig, out RangeConfiguration configuration)
		{
			configuration = ConfigurationBuilder.Build<RangeConfiguration>(xmlConfig, Constants.ExecutorExtensionsNamespace);
		}

		public override void OnValidate(ValidationEngine validationEngine, ExecutionContext context)
		{
			validationEngine.Validate.That.String(Configuration.TargetAddress, RangeConfiguration.TargetAddressAttributeName)
				.IsNotNullOrEmpty();

			validationEngine.Validate.That.Reflected(Configuration)
				.PropertyValuesContainNot("%");

			validationEngine.Validate.That.Excel(context.TargetWorkbook)
				.WorksheetPreFixIsDefined(Configuration.TargetAddress);

			validationEngine.Validate.That.Excel(context.TargetWorkbook)
				.WorksheetExists(Configuration.TargetAddress);
		}

		public override string Name
		{
			get { return ExecutorName; }
		}

		public override string Type
		{
			get { return ExecutorType; }
		}

		public override string ActionId
		{
			get { return ExecutorAction; }
		}
	}
}
